import com.mt.system.domain.Permission;
import com.mt.components.general.DataBox;
import com.mt.components.general.Node;
import com.mt.components.tab.TabFactory;
import com.mt.components.utils.IconUtility;
import com.mt.components.utils.ImageSource;
import com.mt.components.utils.RemoteFactory;

import flash.events.MouseEvent;
import flash.utils.getDefinitionByName;

import mx.containers.Box;
import mx.containers.VBox;
import mx.controls.Button;
import mx.controls.HRule;
import mx.controls.LinkButton;
import mx.core.Container;
import mx.core.FlexGlobals;
import mx.rpc.events.ResultEvent;

[Bindable]private var menus:DataBox = new DataBox();

private function initData():void {
	TabFactory.getInstance().tab = FlexGlobals.topLevelApplication.superTab;
	RemoteFactory.getInstance().user = FlexGlobals.topLevelApplication.user;
	
	for each(var permission:Permission in FlexGlobals.topLevelApplication.permissions){
		var node:Node = new Node();
		node.name = permission.menu.name
		node.icon = permission.menu.icon;
		node.data = permission;
		menus.addNode(node);
		for each(var child:Permission in permission.children){
			var childNode:Node = new Node();
			childNode.name = child.menu.name;
			childNode.icon = child.menu.icon;
			childNode.action = child.menu.action;
			childNode.parent = node;
			childNode.data = child;
			menus.addNode(childNode);
		}
	}
	initMenus();
}

private function initMenus():void {
	for each(var node:Node in menus.rootNodes){
		var vbox:VBox = new VBox();
		vbox.percentWidth = 100;
		vbox.percentHeight = 100;
		vbox.label = node.name;
		vbox.data = node;
		vbox.setStyle("verticalGap" , 5);
		vbox.icon = IconUtility.getClass(vbox , node.icon , 40 , 40);
		this.addChild(vbox);
		
		for each(var child:Node in node.children){
			var linkButton:LinkButton = new LinkButton();
			linkButton.setStyle("icon" , IconUtility.getClass(linkButton , child.icon , 25 , 25));
			linkButton.label = child.name;
			linkButton.setStyle("textAlign" , "left");
			linkButton.percentWidth = 100;
			linkButton.data = child;
			vbox.addChild(linkButton);
			
			linkButton.addEventListener(MouseEvent.CLICK , menuClick);
			
			var hrule:HRule = new HRule();
			hrule.percentWidth = 100;
			hrule.setStyle("strokeWidth" , 1);
			hrule.setStyle("strokeColor" , "#FFFFFF");
			vbox.addChild(hrule);
		}
	}
	
	this.selectedIndex = 0;
}

protected function menuClick(event:MouseEvent):void {
	var node:Node = (event.target as Button).data as Node;
	var classRefrence:Class = getDefinitionByName(node.action) as Class;
	var box:Container = new classRefrence() as Container;
	box.data = node.data;
	box.styleName = "page";
	TabFactory.getInstance().addTab(box , node.name , node.icon);
}
